package com.cdhong.shop.backend.controller;


import com.cdhong.shop.backend.entity.Category;
import com.cdhong.shop.backend.entity.ResponseEntity;
import com.cdhong.shop.backend.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author CDHong
 * @since 2024-04-17
 */
@CrossOrigin
@RestController
@RequestMapping("/category")
public class CategoryController {


    @Autowired
    private ICategoryService categoryService;


    /**
     * 查询分类列表
     * @return 返回结果集
     */
    @GetMapping("list")
    public ResponseEntity list(){
        List<Category> list = categoryService.list();
        if(list.isEmpty()) return ResponseEntity.error("没有数据集");
        return ResponseEntity.data(list);
    }


    /**
     * 查询单个分类
     * @param id 分类ID
     * @return 返回当前ID对应的分类信息
     */
    @GetMapping("one")
    public ResponseEntity one(Integer id){
        Category category = categoryService.getById(id);
        if(Objects.nonNull(category)) return ResponseEntity.data(category);
        return ResponseEntity.error("该分类没有数据，请检查ID");
    }


    /**
     * 添加/修改分类
     * @param category 分类数据对象：`pid` 分类上级 id，0 表示无
     * @return 返回是否操作分类成功
     */
    @PostMapping({"add","edit"})
    public ResponseEntity add(@RequestBody Category category){
        boolean flg = categoryService.saveOrUpdate(category);
        if(flg) return ResponseEntity.ok("操作分类成功");
        return ResponseEntity.error("操作分类失败");
    }

    /**
     * 删除分类
     * @param map 分类ID
     * @return 返回是否删除分类成功
     */
    @PostMapping("del")
    public ResponseEntity del(@RequestBody Map<String,Integer> map){
        boolean flg = categoryService.removeById(map.get("id"));
        if(flg) return ResponseEntity.ok("删除分类成功！！");
        return ResponseEntity.error("删除分类失败！！");
    }


}
